package com.webserver.http;

import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * Author：毕龙
 * Date: 2022/9/21 8:48
 */
public class HttpServletRequest {
    private Socket socket;

    //请求行相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    //消息头相关信息
    private HashMap<String,String> headers = new HashMap<String,String>();



    public HttpServletRequest(Socket socket)throws Exception{
        this.socket= socket;

        //1.解析请求行
        parseRequestLine();

        //2.解析消息头
        parseHeaders();

        //3.解析消息正文
        paserContent();

    }



    //解析请求行
    private void parseRequestLine()throws Exception{
        String line = readLine();

        if(line.isEmpty()){//若请求行是空字符串 则说明本次为空请求
            throw new EmptyRequestException("request is empty");
        }
        System.out.println("请求行："+line);
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);

    }

    //解析消息头
    private void parseHeaders()throws Exception{
        //读取消息头
        while (true){
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头："+line);
            String[] data = line.split("\\s");
            //key:connection value:keep-alive
            headers.put(data[0],data[1]);//key:消息头的名字 value:消息头的值
        }
        System.out.println("headers:"+headers);
    }

    //解析消息正文
    private void paserContent(){}


    //获取一行信息
    private String readLine()throws Exception{
        //当对同一个socket调用多次getInputStream方法时 获取回来的输入流始终是同一条流
        InputStream is = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char pre = 'a',cur='a';
        while((d=is.read())!=1){
            cur = (char) d;
            if(pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }


    public String getMethod(){
        return method;
    }

    public String getUri(){
        return uri;
    }

    public String getProtocol(){
        return protocol;
    }

    public String getHeaders(String name){
        return headers.get(name);
    }

}
